document.addEventListener('DOMContentLoaded', function() {
    // 页面加载时获取存款类型
    fetch('/admincard/get_deposit_types')
        .then(response => response.json())
        .then(data => {
            const savingSelect = document.getElementById('savingID');
            savingSelect.innerHTML = '<option value="">请选择存款类型</option>';

            data.forEach(dt => {
                const option = document.createElement('option');
                option.value = dt.savingID;
                option.textContent = dt.savingName;
                savingSelect.appendChild(option);
            });
        })
        .catch(error => {
            console.error('获取存款类型失败:', error);
            alert('获取存款类型失败');
        });

    // 搜索按钮事件
    document.getElementById('searchBtn').addEventListener('click', function() {
        const cardId = document.getElementById('cardIdSearch').value.trim();
        const customerId = document.getElementById('customerIdSearch').value.trim();

        let params = new URLSearchParams();
        if (cardId) params.append('cardIdSearch', cardId);
        if (customerId) params.append('customerIdSearch', customerId);

        window.location.href = `${window.location.pathname}?${params.toString()}`;
    });

    // 添加银行卡按钮
    document.getElementById('addCardBtn').addEventListener('click', function() {
        const modal = new bootstrap.Modal(document.getElementById('cardModal'));
        document.getElementById('modalTitle').textContent = '添加新银行卡';
        document.getElementById('cardForm').reset();
        modal.show();
    });

    // 导出CSV按钮
    document.getElementById('exportCsvBtn').addEventListener('click', function() {
        const cardId = document.getElementById('cardIdSearch').value.trim();
        const customerId = document.getElementById('customerIdSearch').value.trim();

        let params = new URLSearchParams();
        if (cardId) params.append('cardIdSearch', cardId);
        if (customerId) params.append('customerIdSearch', customerId);

        window.location.href = `/admincard/export_cards_csv?${params.toString()}`;
    });

    // 编辑按钮事件
    document.querySelectorAll('.edit-btn').forEach(btn => {
        btn.addEventListener('click', function() {
            const cardId = this.getAttribute('data-id');

            // 从表格行中获取数据
            const row = this.closest('tr');
            const cells = row.querySelectorAll('td');

            // 填充模态框
            document.getElementById('modalTitle').textContent = '编辑银行卡信息';
            document.getElementById('cardId').value = cardId;
            document.getElementById('savingID').value = row.getAttribute('data-saving-id');
            document.getElementById('openMoney').value = parseFloat(cells[4].textContent);
            document.getElementById('balance').value = parseFloat(cells[5].textContent);
            document.getElementById('IsReportLoss').value = cells[6].textContent;
            document.getElementById('customerID').value = parseInt(cells[7].textContent);

            // 显示模态框
            const modal = new bootstrap.Modal(document.getElementById('cardModal'));
            modal.show();
        });
    });

    // 删除按钮事件
    document.querySelectorAll('.delete-btn').forEach(btn => {
        btn.addEventListener('click', function() {
            const cardId = this.getAttribute('data-id');

            if (confirm(`确定要删除银行卡 ${cardId} 吗？此操作不可恢复！`)) {
                fetch(`/admincard/delete_card/${cardId}`, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    }
                })
                .then(response => response.json())
                .then(data => {
                    if (data.message) {
                        alert(data.message);
                        location.reload();
                    } else if (data.error) {
                        alert(data.error);
                    }
                })
                .catch(error => {
                    console.error('删除失败:', error);
                    alert('删除银行卡失败，请重试');
                });
            }
        });
    });

    // 详细按钮事件
    document.querySelectorAll('.detail-btn').forEach(btn => {
        btn.addEventListener('click', function() {
            const cardId = this.getAttribute('data-id');

            // 获取银行卡详情
            fetch(`/admincard/card_detail/${cardId}`)
                .then(response => response.json())
                .then(data => {
                    if (data.error) {
                        alert(data.error);
                        return;
                    }

                    // 填充详情模态框
                    document.getElementById('detailCardId').textContent = data.cardID;
                    document.getElementById('detailCurID').textContent = data.curID;
                    document.getElementById('detailSavingID').textContent = data.savingID;
                    document.getElementById('detailOpenDate').textContent = data.openDate;
                    document.getElementById('detailOpenMoney').textContent = data.openMoney.toFixed(2);
                    document.getElementById('detailBalance').textContent = data.balance.toFixed(2);
                    document.getElementById('detailStatus').textContent = data.IsReportLoss;
                    document.getElementById('detailCustomerID').textContent = data.customerID;
                    document.getElementById('detailCustomerName').textContent = data.customerName;

                    // 填充交易记录
                    const tbody = document.querySelector('#recentTransactionsTable tbody');
                    tbody.innerHTML = '';

                    if (data.transactions.length > 0) {
                        data.transactions.forEach(trans => {
                            const row = document.createElement('tr');
                            row.innerHTML = `
                                <td>${trans.tradeDate}</td>
                                <td>${trans.tradeType}</td>
                                <td>${trans.tradeMoney.toFixed(2)}</td>
                                <td>${trans.remark || '无'}</td>
                            `;
                            tbody.appendChild(row);
                        });
                    } else {
                        const row = document.createElement('tr');
                        row.innerHTML = '<td colspan="4" class="text-center">无交易记录</td>';
                        tbody.appendChild(row);
                    }

                    // 显示模态框
                    const modal = new bootstrap.Modal(document.getElementById('cardDetailModal'));
                    modal.show();
                })
                .catch(error => {
                    console.error('获取详情失败:', error);
                    alert('获取银行卡详情失败，请重试');
                });
        });
    });

    // 保存银行卡按钮
    document.getElementById('saveCardBtn').addEventListener('click', function() {
        const formData = {
            cardId: document.getElementById('cardId').value,
            curID: 'RMB', // 币种固定为RMB
            savingID: document.getElementById('savingID').value,
            openMoney: document.getElementById('openMoney').value,
            balance: document.getElementById('balance').value,
            IsReportLoss: document.getElementById('IsReportLoss').value,
            customerID: document.getElementById('customerID').value
        };

        const url = formData.cardId ? '/admincard/edit_card' : '/admincard/add_card';
        const method = 'POST';

        fetch(url, {
            method: method,
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded',
            },
            body: new URLSearchParams(formData).toString()
        })
        .then(response => {
            if (response.redirected) {
                window.location.href = response.url;
            } else {
                return response.json();
            }
        })
        .then(data => {
            if (data && data.message) {
                alert(data.message);
                location.reload();
            } else if (data && data.error) {
                alert(data.error);
            }
        })
        .catch(error => {
            console.error('保存失败:', error);
            alert('保存银行卡信息失败，请重试');
        });
    });

    // 挂失银行卡按钮
    document.getElementById('reportLossBtn').addEventListener('click', function() {
        const cardId = document.getElementById('detailCardId').textContent;
        const currentStatus = document.getElementById('detailStatus').textContent;
        const newStatus = currentStatus === '是' ? '否' : '是';
        const confirmText = newStatus === '是'
            ? `确定要挂失银行卡 ${cardId} 吗？挂失后将无法进行任何交易！`
            : `确定要解除银行卡 ${cardId} 的挂失状态吗？`;

        if (confirm(confirmText)) {
            fetch('/admincard/edit_card', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded',
                },
                body: new URLSearchParams({
                    cardId: cardId,
                    IsReportLoss: newStatus
                }).toString()
            })
            .then(response => {
                if (response.redirected) {
                    window.location.href = response.url;
                } else {
                    return response.json();
                }
            })
            .then(data => {
                if (data && data.message) {
                    alert(data.message);
                    document.getElementById('detailStatus').textContent = newStatus;
                    // 更新表格中的状态显示
                    document.querySelectorAll('.detail-btn').forEach(btn => {
                        if (btn.getAttribute('data-id') === cardId) {
                            const row = btn.closest('tr');
                            row.querySelector('td:nth-child(7)').textContent = newStatus;
                        }
                    });
                } else if (data && data.error) {
                    alert(data.error);
                }
            })
            .catch(error => {
                console.error('操作失败:', error);
                alert('操作失败，请重试');
            });
        }
    });

    // 重置密码按钮
    document.getElementById('resetPasswordBtn').addEventListener('click', function() {
        const cardId = document.getElementById('detailCardId').textContent;
        document.getElementById('resetCardId').value = cardId;

        const modal = new bootstrap.Modal(document.getElementById('resetPasswordModal'));
        modal.show();
    });

    // 确认重置密码按钮
    document.getElementById('confirmResetBtn').addEventListener('click', function() {
        const cardId = document.getElementById('resetCardId').value;
        const newPassword = document.getElementById('newPassword').value;
        const confirmPassword = document.getElementById('confirmPassword').value;

        if (newPassword !== confirmPassword) {
            alert('两次输入的密码不一致！');
            return;
        }

        if (newPassword.length < 6 || newPassword.length > 20) {
            alert('密码长度必须在6-20位之间！');
            return;
        }

        fetch('/admincard/reset_password', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({
                cardId: cardId,
                newPassword: newPassword
            })
        })
        .then(response => response.json())
        .then(data => {
            if (data.message) {
                alert(data.message);
                // 关闭重置密码模态框
                const modal = bootstrap.Modal.getInstance(document.getElementById('resetPasswordModal'));
                modal.hide();
                // 清空表单
                document.getElementById('resetPasswordForm').reset();
            } else if (data.error) {
                alert(data.error);
            }
        })
        .catch(error => {
            console.error('重置密码失败:', error);
            alert('重置密码失败，请重试');
        });
    });
});